<template>
  <div class="main">
    <!-- 搜索表单 -->
    <el-form
      ref="formRef"
      :inline="true"
      :model="form"
      class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px] overflow-auto"
    >
      <el-form-item prop="account">
        <el-select
          v-model="form.account"
          placeholder="选择广告账户"
          clearable
          filterable
          class="!w-[180px]"
          @change="onSearch"
        >
          <el-option
            v-for="item in adAccounts"
            :key="item.adAccountId"
            :label="item.adAccountName"
            :value="item.adAccountId"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="searchName">
        <el-input
          v-model="form.searchName"
          :placeholder="getSearchPlaceholder()"
          clearable
          class="!w-[180px]"
        />
      </el-form-item>
      <!-- <el-form-item prop="timeZoneIana">
        <el-select
          v-model="form.timeZoneIana"
          placeholder="选择时区"
          class="!w-[180px]"
          @change="onSearch"
        >
          <el-option
            v-for="item in timeZoneOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[
            new Date(2000, 1, 1, 0, 0, 0),
            new Date(2000, 1, 1, 23, 59, 59)
          ]"
          @change="handleDateRangeChange"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon('ri:search-line')"
          :loading="loading"
          @click="onSearch"
        >
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <div class="table-container">
      <!-- tab 切换组件移动到表格区域顶部 -->
      <el-tabs
        v-model="activeTab"
        class="mb-4 custom-tabs"
        @tab-change="handleTabChange"
      >
        <el-tab-pane
          v-for="tab in tabs"
          :key="tab.name"
          :label="tab.label"
          :name="tab.name"
        >
          <template #label>
            <span class="tab-label">
              {{ tab.label }}
            </span>
          </template>
        </el-tab-pane>
      </el-tabs>

      <!-- 表格标题和内容 -->
      <PureTableBar
        :key="activeTab"
        :title="tabs.find(t => t.name === activeTab)?.label"
        :columns="columns"
        @refresh="onSearch"
      >
        <template #buttons>
          <el-popconfirm
            v-if="selectItems.length"
            title="是否确认开启?"
            icon="none"
            @confirm="handleAction('open')"
          >
            <template #reference>
              <el-button class="reset-margin" type="primary"> 开启</el-button>
            </template>
          </el-popconfirm>
          <el-popconfirm
            v-if="selectItems.length"
            title="是否确认关闭?"
            icon="none"
            @confirm="handleAction('close')"
          >
            <template #reference>
              <el-button class="reset-margin" type="warning"> 关闭</el-button>
            </template>
          </el-popconfirm>
          <el-popconfirm
            v-if="selectItems.length"
            title="是否确认删除?"
            @confirm="handleAction('delete')"
          >
            <template #reference>
              <el-button class="reset-margin" type="danger"> 删除</el-button>
            </template>
          </el-popconfirm>
          <el-button
            type="primary"
            :icon="useRenderIcon(AddFill)"
            @click="handleCreateClick"
          >
            创建{{ tabs.find(t => t.name === activeTab)?.label }}
          </el-button>
        </template>
        <template v-slot="{ size, dynamicColumns }">
          <pure-table
            ref="tableRef"
            align-whole="center"
            showOverflowTooltip
            table-layout="auto"
            :loading="loading"
            :size="size"
            adaptive
            :adaptiveConfig="{ offsetBottom: 80 }"
            :data="dataList"
            :columns="dynamicColumns"
            :pagination="pagination"
            :paginationSmall="size === 'small' ? true : false"
            :header-cell-style="{
              background: 'var(--el-fill-color-light)',
              color: 'var(--el-text-color-primary)'
            }"
            class="promotion-table"
            @selection-change="handleSelectionChange"
            @page-size-change="handleSizeChange"
            @page-current-change="handleCurrentChange"
          >
            <template v-if="selectItems.length" #append>
              <div style="padding: 10px; text-align: left">
                已选择 {{ selectItems.length }} 项
              </div>
            </template>
          </pure-table>
        </template>
      </PureTableBar>
    </div>
    <!-- 创建广告组弹窗 -->
    <el-dialog
      v-model="unitDialogVisible"
      title="选择广告计划"
      width="500px"
      destroy-on-close
    >
      <el-form ref="unitFormRef" :model="unitForm" label-width="120px">
        <!-- 广告计划 -->
        <el-form-item label="广告计划" prop="campaignId">
          <campaign-selector
            v-model:valueId="unitForm.campaignId"
            v-model:valueName="unitSelectedCampaignName"
            :adAccounts="adAccounts"
            :baseParams="baseSearchParams"
            @select="handleUnitCampaignSelect"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="unitDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUnitConfirm">确认</el-button>
      </template>
    </el-dialog>

    <!-- 创建广告创意弹窗 -->
    <el-dialog
      v-model="creativeDialogVisible"
      title="选择广告计划和广告组"
      width="500px"
      destroy-on-close
    >
      <el-form ref="creativeFormRef" :model="creativeForm" label-width="120px">
        <!-- 广告计划 -->
        <el-form-item label="广告计划" prop="campaignId">
          <campaign-selector
            v-model:valueId="creativeForm.campaignId"
            v-model:valueName="creativeSelectedCampaignName"
            :adAccounts="adAccounts"
            :baseParams="baseSearchParams"
            @select="handleCreativeCampaignSelect"
          />
        </el-form-item>
        <!-- 广告组 -->
        <el-form-item label="广告组" prop="unitId">
          <campaign-selector
            v-model:valueId="creativeForm.unitId"
            v-model:valueName="creativeSelectedUnitName"
            title="广告组"
            placeholder="请选择广告组"
            type="unit"
            nameField="unitName"
            idField="unitId"
            :adAccounts="adAccounts"
            :baseParams="{
              ...baseSearchParams,
              campaignId: creativeForm.campaignId
            }"
            :disabled="!creativeForm.campaignId"
            @select="handleCreativeUnitSelect"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="creativeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreativeConfirm"
          >确认</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, h } from "vue";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Refresh from "@iconify-icons/ep/refresh";
import AddFill from "@iconify-icons/ri/add-circle-line";
import { useRouter } from "vue-router";
import {
  getCampaignSelect,
  getCampaignList,
  getAdAccounts,
  getCreativeList,
  getUnitList,
  campaignUpdateStatus,
  campaignDelete,
  updateUnitStatus,
  deleteUnit,
  updateCreativeStatus,
  deleteCreative
} from "@/api/promotion";
import { accountCreate } from "@/api/user";

import dayjs from "dayjs";
import { ElMessage } from "element-plus";
import type { TableColumns } from "@pureadmin/table";
import { setSessionStorage } from "@/utils/storage";
import CampaignSelector from "./components/CampaignSelector.vue";
import { ElTag } from "element-plus";
import { getSessionStorage, removeSessionStorage } from "@/utils/storage";

defineOptions({
  name: "Promotion"
});

const router = useRouter();
const formRef = ref();
const tableRef = ref();
const loading = ref(false);

// 弹窗相关状态
const unitDialogVisible = ref(false);
const creativeDialogVisible = ref(false);

// 广告组表单
const unitForm = ref({
  campaignId: ""
});
const unitSelectedCampaignName = ref("");
const unitSelectedCampaign = ref(null);

// 广告创意表单
const creativeForm = ref({
  campaignId: "",
  unitId: ""
});
const creativeSelectedCampaignName = ref("");
const creativeSelectedUnitName = ref("");
const creativeSelectedCampaign = ref(null);
const creativeSelectedUnit = ref(null);

// 广告创意广告组选择事件
const handleCreativeUnitSelect = unit => {
  creativeSelectedUnit.value = unit;
  creativeForm.value.unitId = unit.unitId;
};

// 广告组广告计划选择事件
const handleUnitCampaignSelect = campaign => {
  console.log("handleUnitCampaignSelect campaign = ", campaign);
  unitSelectedCampaign.value = campaign;
};

// 广告创意广告计划选择事件
const handleCreativeCampaignSelect = campaign => {
  creativeSelectedCampaign.value = campaign;
  // 更新 campaignId
  creativeForm.value.campaignId = campaign.campaignId;
  // 清空已选择的广告组
  creativeForm.value.unitId = "";
  creativeSelectedUnitName.value = "";
  creativeSelectedUnit.value = null;
  console.log(creativeForm, "--creativeForm--");
};

// 处理创建按钮点击
const handleCreateClick = () => {
  //清除缓存数据
  removeSessionStorage("selectedCampaign");
  removeSessionStorage("selectedUnit");
  switch (activeTab.value) {
    case "campaign":
      // 广告计划 - 直接跳转
      router.push({
        path: "/promotion/creation",
        query: {
          type: "campaign"
        }
      });
      break;
    case "unit":
      // 广告组 - 打开选择广告计划弹窗
      unitDialogVisible.value = true;
      break;
    case "creative":
      // 广告创意 - 打开选择广告计划和广告组弹窗
      creativeDialogVisible.value = true;
      break;
  }
};

// 广告组弹窗确认
const handleUnitConfirm = () => {
  if (!unitSelectedCampaign.value) {
    ElMessage.warning("请选择广告计划");
    return;
  }

  // 存储选中的广告计划数据
  setSessionStorage(
    "selectedCampaign",
    unitSelectedCampaign.value // 使用完整的选中对象
  );

  // 跳转到创建页面
  router.push({
    path: "/promotion/creation",
    query: {
      type: "unit"
    }
  });

  unitDialogVisible.value = false;
};

// 广告创意弹窗确认
const handleCreativeConfirm = () => {
  if (!creativeForm.value.campaignId) {
    ElMessage.warning("请选择广告计划");
    return;
  }

  if (!creativeForm.value.unitId) {
    ElMessage.warning("请选择广告组");
    return;
  }

  // 存储选中的数据
  setSessionStorage("selectedCampaign", creativeSelectedCampaign.value);
  console.log(creativeSelectedUnit.value, "creativeSelectedUnit.value");
  if (creativeSelectedUnit.value.devicePriceInfoList.length > 0) {
    const min =
      creativeSelectedUnit.value.devicePriceInfoList[0].devicePriceMin;
    const max =
      creativeSelectedUnit.value.devicePriceInfoList[0].devicePriceMax;
    creativeSelectedUnit.value.devicePriceInfoList = [min, max];
  }
  setSessionStorage("selectedUnit", creativeSelectedUnit.value);

  // 跳转到创建页面
  router.push({
    path: "/promotion/creation",
    query: {
      type: "creative"
    }
  });

  creativeDialogVisible.value = false;
};

const form = ref({
  account: 0,
  searchName: "",
  timeZoneIana: "UTC+8",
  dataBeginTime: dayjs().subtract(7, "day").valueOf(),
  dataEndTime: dayjs().valueOf()
});

const rules = {
  accountId: [{ required: true, message: "请选择广告账户", trigger: "change" }],
  marketingType: [
    { required: true, message: "请选择推广对象", trigger: "change" }
  ],
  deliveryStrategy: [
    { required: true, message: "请选择出价策略", trigger: "change" }
  ],
  campaignName: [
    { required: true, message: "请输入计划名称", trigger: "blur" },
    { max: 100, message: "超出可输入最长计划名称", trigger: "blur" }
  ],
  dayBudget: [
    { required: true, message: "请输入每日固定预算", trigger: "blur" },
    {
      type: "number",
      min: 1,
      message: "请输入大于1的每日预算",
      trigger: "blur"
    }
  ]
};
const campaignColumns = ref<TableColumns[]>([
  {
    type: "selection",
    width: 50
  },
  {
    label: "广告账户名称",
    prop: "accountName",
    minWidth: 150
  },
  {
    label: "计划名称",
    prop: "campaignName",
    minWidth: 150
  },
  {
    label: "投放状态",
    prop: "status",
    formatter: (row: any) => formatStatus(row.status)
  },
  {
    label: "预算",
    prop: "dayBudget",
    formatter: (row: any) => {
      if (row.dayBudget) return formatCost(row.dayBudget);
      return row.budgetSchedule ? formatCost(row.budgetSchedule) : "不限";
    }
  },
  {
    label: "出价策略",
    prop: "deliveryStrategy",
    formatter: (row: any) => formatDeliveryStrategy(row.deliveryStrategy)
  },
  {
    label: "推广目的",
    prop: "marketingType",
    formatter: (row: any) => formatMarketingType(row.marketingType)
  },
  {
    label: "数据源头",
    prop: "dataGenerationSource",
    formatter: (row: any) => formatDataSource(row.dataGenerationSource)
  },
  {
    label: "消耗",
    prop: "cost",
    formatter: (row: any) => formatCost(row.cost)
  },
  {
    label: "曝光数",
    prop: "exposure"
  },
  {
    label: "点击数",
    prop: "click"
  },
  {
    label: "转化数",
    prop: "action"
  },
  {
    label: "CPM",
    prop: "cpm",
    formatter: (row: any) => formatCost(row.cpm)
  },
  {
    label: "CPC",
    prop: "cpc",
    formatter: (row: any) => formatCost(row.cpc)
  },
  {
    label: "CTR",
    prop: "ctr",
    formatter: (row: any) => formatRate(row.ctr)
  },
  {
    label: "CVR",
    prop: "cvr",
    formatter: (row: any) => formatRate(row.cvr)
  },
  {
    label: "CPA",
    prop: "cpa",
    formatter: (row: any) => formatCost(row.cpa)
  },
  {
    label: "注册数（转化时间）",
    prop: "registration"
  },
  {
    label: "注册成本（转化时间）",
    prop: "costPerRegistration",
    formatter: (row: any) => formatCost(row.costPerRegistration)
  },
  {
    label: "注册转化率（转化时间）",
    prop: "registrationRate",
    formatter: (row: any) => formatRate(row.registrationRate)
  },
  {
    label: "加购数（转化时间）",
    prop: "addToCart"
  },
  {
    label: "加购成本（转化时间）",
    prop: "costPerAddToCart",
    formatter: (row: any) => formatCost(row.costPerAddToCart)
  },
  {
    label: "加购率",
    prop: "addToCartRate",
    formatter: (row: any) => formatRate(row.addToCartRate)
  },
  {
    label: "激活数",
    prop: "activation"
  },
  {
    label: "激活成本",
    prop: "costPerActivation",
    formatter: (row: any) => formatCost(row.costPerActivation)
  },
  {
    label: "激活率",
    prop: "activationRate",
    formatter: (row: any) => formatRate(row.activationRate)
  },
  {
    label: "去重付费数（转化时间）",
    prop: "uniquePurchase"
  },
  {
    label: "去重付费成本（转化时间）",
    prop: "uniquePurchaseRate",
    formatter: (row: any) => formatCost(row.uniquePurchaseRate)
  },
  {
    label: "去重关键行为数（转化时间）",
    prop: "uniqueKeyInAppAction"
  },
  {
    label: "去重关键行为成本（转化时间）",
    prop: "costPerUniqueKeyInAppAction",
    formatter: (row: any) => formatCost(row.costPerUniqueKeyInAppAction)
  }
]);

const unitColumns = ref<TableColumns[]>([
  {
    type: "selection",
    width: 50
  },
  {
    label: "广告账户名称",
    prop: "accountName",
    minWidth: 150
  },
  {
    label: "广告计划名称",
    prop: "campaignName",
    minWidth: 150
  },
  {
    label: "广告组名称",
    prop: "unitName",
    minWidth: 150
  },
  {
    label: "投放状态",
    prop: "status",
    formatter: (row: any) => formatStatus(row.status)
  },
  {
    label: "预算",
    prop: "dayBudget",
    formatter: (row: any) => {
      if (row.dayBudget) return formatCost(row.dayBudget);
      return row.budgetSchedule ? formatCost(row.budgetSchedule) : "不限";
    }
  },
  {
    label: "出价策略",
    prop: "deliveryStrategy",
    formatter: (row: any) => formatDeliveryStrategy(row.deliveryStrategy)
  },
  {
    label: "推广目的",
    prop: "marketingType",
    formatter: (row: any) => formatMarketingType(row.marketingType)
  },
  {
    label: "数据源头",
    prop: "dataGenerationSource",
    formatter: (row: any) => formatDataSource(row.dataGenerationSource)
  },
  {
    label: "消耗",
    prop: "cost",
    formatter: (row: any) => formatCost(row.cost)
  },
  {
    label: "曝光数",
    prop: "exposure"
  },
  {
    label: "点击数",
    prop: "click"
  },
  {
    label: "转化数",
    prop: "action"
  },
  {
    label: "CPM",
    prop: "cpm",
    formatter: (row: any) => formatCost(row.cpm)
  },
  {
    label: "CPC",
    prop: "cpc",
    formatter: (row: any) => formatCost(row.cpc)
  },
  {
    label: "CTR",
    prop: "ctr",
    formatter: (row: any) => formatRate(row.ctr)
  },
  {
    label: "CVR",
    prop: "cvr",
    formatter: (row: any) => formatRate(row.cvr)
  },
  {
    label: "CPA",
    prop: "cpa",
    formatter: (row: any) => formatCost(row.cpa)
  },
  {
    label: "注册数（转化时间）",
    prop: "registration"
  },
  {
    label: "注册成本（转化时间）",
    prop: "costPerRegistration",
    formatter: (row: any) => formatCost(row.costPerRegistration)
  },
  {
    label: "注册转化率（转化时间）",
    prop: "registrationRate",
    formatter: (row: any) => formatRate(row.registrationRate)
  },
  {
    label: "加购数（转化时间）",
    prop: "addToCart"
  },
  {
    label: "加购成本（转化时间）",
    prop: "costPerAddToCart",
    formatter: (row: any) => formatCost(row.costPerAddToCart)
  },
  {
    label: "加购率",
    prop: "addToCartRate",
    formatter: (row: any) => formatRate(row.addToCartRate)
  },
  {
    label: "激活数",
    prop: "activation"
  },
  {
    label: "激活成本",
    prop: "costPerActivation",
    formatter: (row: any) => formatCost(row.costPerActivation)
  },
  {
    label: "激活率",
    prop: "activationRate",
    formatter: (row: any) => formatRate(row.activationRate)
  },
  {
    label: "去重付费数（转化时间）",
    prop: "uniquePurchase"
  },
  {
    label: "去重付费成本（转化时间）",
    prop: "uniquePurchaseRate",
    formatter: (row: any) => formatCost(row.uniquePurchaseRate)
  },
  {
    label: "去重关键行为数（转化时间）",
    prop: "uniqueKeyInAppAction"
  },
  {
    label: "去重关键行为成本（转化时间）",
    prop: "costPerUniqueKeyInAppAction",
    formatter: (row: any) => formatCost(row.costPerUniqueKeyInAppAction)
  }
]);

const creativeColumns = ref<TableColumns[]>([
  {
    type: "selection",
    width: 50
  },
  {
    label: "广告账户名称",
    prop: "accountName",
    minWidth: 100
  },
  {
    label: "广告计划名称",
    prop: "campaignName",
    minWidth: 150
  },
  {
    label: "广告组名称",
    prop: "unitName",
    minWidth: 150
  },
  {
    label: "创意名称",
    prop: "creativeName",
    minWidth: 150
  },
  {
    label: "投放状态",
    prop: "status",
    formatter: (row: any) => formatStatus(row.status)
  },
  {
    label: "预算",
    prop: "dayBudget",
    formatter: (row: any) => {
      if (row.dayBudget) return formatCost(row.dayBudget);
      return row.budgetSchedule ? formatCost(row.budgetSchedule) : "不限";
    }
  },
  {
    label: "出价策略",
    prop: "deliveryStrategy",
    formatter: (row: any) => formatDeliveryStrategy(row.deliveryStrategy)
  },
  {
    label: "推广目的",
    prop: "marketingType",
    formatter: (row: any) => formatMarketingType(row.marketingType)
  },
  {
    label: "数据源头",
    prop: "dataGenerationSource",
    formatter: (row: any) => formatDataSource(row.dataGenerationSource)
  },
  {
    label: "消耗",
    prop: "cost",
    formatter: (row: any) => formatCost(row.cost)
  },
  {
    label: "曝光数",
    prop: "exposure"
  },
  {
    label: "点击数",
    prop: "click"
  },
  {
    label: "转化数",
    prop: "action"
  },
  {
    label: "CPM",
    prop: "cpm",
    formatter: (row: any) => formatCost(row.cpm)
  },
  {
    label: "CPC",
    prop: "cpc",
    formatter: (row: any) => formatCost(row.cpc)
  },
  {
    label: "CTR",
    prop: "ctr",
    formatter: (row: any) => formatRate(row.ctr)
  },
  {
    label: "CVR",
    prop: "cvr",
    formatter: (row: any) => formatRate(row.cvr)
  },
  {
    label: "CPA",
    prop: "cpa",
    formatter: (row: any) => formatCost(row.cpa)
  },
  {
    label: "注册数（转化时间）",
    prop: "registration"
  },
  {
    label: "注册成本（转化时间）",
    prop: "costPerRegistration",
    formatter: (row: any) => formatCost(row.costPerRegistration)
  },
  {
    label: "注册转化率（转化时间）",
    prop: "registrationRate",
    formatter: (row: any) => formatRate(row.registrationRate)
  },
  {
    label: "加购数（转化时间）",
    prop: "addToCart"
  },
  {
    label: "加购成本（转化时间）",
    prop: "costPerAddToCart",
    formatter: (row: any) => formatCost(row.costPerAddToCart)
  },
  {
    label: "加购率",
    prop: "addToCartRate",
    formatter: (row: any) => formatRate(row.addToCartRate)
  },
  {
    label: "激活数",
    prop: "activation"
  },
  {
    label: "激活成本",
    prop: "costPerActivation",
    formatter: (row: any) => formatCost(row.costPerActivation)
  },
  {
    label: "激活率",
    prop: "activationRate",
    formatter: (row: any) => formatRate(row.activationRate)
  },
  {
    label: "去重付费数（转化时间）",
    prop: "uniquePurchase"
  },
  {
    label: "去重付费成本（转化时间）",
    prop: "uniquePurchaseRate",
    formatter: (row: any) => formatCost(row.uniquePurchaseRate)
  },
  {
    label: "去重关键行为数（转化时间）",
    prop: "uniqueKeyInAppAction"
  },
  {
    label: "去重关键行为成本（转化时间）",
    prop: "costPerUniqueKeyInAppAction",
    formatter: (row: any) => formatCost(row.costPerUniqueKeyInAppAction)
  }
]);

const dataList = ref([]);
const pagination = ref({
  total: 0,
  pageSize: 10,
  currentPage: 1
});

const handleSizeChange = async (val: number) => {
  pagination.value.pageSize = val;
  await loadTableData();
};

const handleCurrentChange = async (val: number) => {
  pagination.value.currentPage = val;
  await loadTableData();
};
const handleSelectionChange = async (val: any) => {
  console.log("handleSelectionChange", val);
  if (activeTab.value == "campaign") {
    campaignSelectItems.value = val;
  }
  if (activeTab.value == "unit") {
    unitSelectItems.value = val;
  }
  if (activeTab.value == "creative") {
    creativeSelectItems.value = val;
  }
  console.log(val);
};

const handleAction = async (type: string) => {
  const openStatus = {
    open: 1,
    close: 2
  };
  const params = {
    adAccountId: 0,
    ids: []
  };
  selectItems.value.forEach(item => {
    params.adAccountId = item.adAccountId;
    params.ids.push(item.campaignId);
  });
  switch (activeTab.value) {
    case "campaign":
      if (type == "delete") {
        await campaignDelete({
          adAccountId: params.adAccountId,
          campaignIdList: params.ids
        });
      } else {
        await campaignUpdateStatus({
          adAccountId: params.adAccountId,
          openStatus: openStatus[type],
          campaignIdList: params.ids
        });
      }
      selectItems.value = [];
      await loadTableData();
      return;
    case "unit":
      if (type == "delete") {
        await deleteUnit({
          adAccountId: params.adAccountId,
          unitIdList: params.ids
        });
      } else {
        await updateUnitStatus({
          adAccountId: params.adAccountId,
          openStatus: openStatus[type],
          unitIdList: params.ids
        });
      }
      selectItems.value = [];
      await loadTableData();
      return;
    case "creative":
      if (type == "delete") {
        await deleteCreative({
          adAccountId: params.adAccountId,
          creativeIdList: params.ids
        });
      } else {
        await updateCreativeStatus({
          adAccountId: params.adAccountId,
          openStatus: openStatus[type],
          creativeIdList: params.ids
        });
      }
      selectItems.value = [];
      await loadTableData();
      return;
    default:
      return [];
  }
};

// 添加 tab 相关的代码
const activeTab = ref("campaign"); // 默认选中广告计划tab

// 定义 tab 选项
const tabs = computed(() => [
  {
    name: "campaign",
    label: `广告计划${campaignSelectItems.value.length ? ` (${campaignSelectItems.value.length})` : ""}`
  },
  {
    name: "unit",
    label: `广告组${unitSelectItems.value.length ? ` (${unitSelectItems.value.length})` : ""}`
  },
  {
    name: "creative",
    label: `广告创意${creativeSelectItems.value.length ? ` (${creativeSelectItems.value.length})` : ""}`
  }
]);

const campaignSelectItems = ref([]);
const unitSelectItems = ref([]);
const creativeSelectItems = ref([]);
const selectItems = computed(() => {
  switch (activeTab.value) {
    case "campaign":
      return campaignSelectItems.value;
    case "unit":
      return unitSelectItems.value;
    case "creative":
      return creativeSelectItems.value;
    default:
      return [];
  }
});

watch(campaignSelectItems, (newVal, oldValue) => {
  if (newVal.length < oldValue.length) {
    unitSelectItems.value = [];
    creativeSelectItems.value = [];
  }
});

watch(unitSelectItems, (newVal, oldValue) => {
  if (newVal.length < oldValue.length) {
    creativeSelectItems.value = [];
  }
});

// 确保根据当前激活的标签返回正确的列配置
const columns = computed(() => {
  console.log("当前激活的标签:", activeTab.value);

  const addMinWidth = (cols: TableColumns[]) => {
    return cols.map(col => {
      if (col.type === "selection") {
        return { ...col, width: 50 };
      }
      return { ...col, minWidth: 150 };
    });
  };

  switch (activeTab.value) {
    case "campaign":
      return addMinWidth(campaignColumns.value);
    case "unit":
      return addMinWidth(unitColumns.value);
    case "creative":
      return addMinWidth(creativeColumns.value);
    default:
      return [];
  }
});

// 处理 tab 切换
const handleTabChange = async (tab: string) => {
  console.log("标签切换到:", tab);
  activeTab.value = tab;
  pagination.value.currentPage = 1;
  // 重置数据列表，避免显示旧数据
  dataList.value = [];

  // 重新加载表格数据
  await loadTableData();

  const keyMap = {
    campaign: "campaignId",
    unit: "unitId",
    creative: "creativeId"
  };
  const key = keyMap[tab];

  dataList.value
    .filter(v => selectItems.value.map(v => v[key]).includes(v[key]))
    .forEach(row => {
      tableRef.value.getTableRef().toggleRowSelection(row, true);
    });
};

// 根据当前选中的 tab 加载对应的数据
const loadTableData = async () => {
  loading.value = true;
  try {
    const params = {
      adAccountId: form.value.account,
      page: pagination.value.currentPage,
      size: pagination.value.pageSize,
      timeZoneIana: form.value.timeZoneIana,
      dataBeginTime: form.value.dataBeginTime,
      dataEndTime: form.value.dataEndTime
    };

    let data;
    switch (activeTab.value) {
      case "campaign":
        // 搜索计划名称
        if (form.value.searchName) {
          params["campaignName"] = form.value.searchName;
        }
        data = await getCampaignList(params);
        console.log("广告计划数据:", data);
        break;
      case "unit":
        // 搜索广告组名称
        if (form.value.searchName) {
          params["unitName"] = form.value.searchName;
        }
        if (campaignSelectItems.value.length > 0) {
          params["campaignIdList"] = campaignSelectItems.value;
        }
        data = await getUnitList(params);
        console.log("广告组数据:", data);
        // 检查单条数据结构
        if (data?.list?.[0]) {
          console.log("广告组第一条数据:", data.list[0]);
          console.log("广告组名称字段:", data.list[0].unitName);
        }
        break;
      case "creative":
        // 搜索创意名称
        if (form.value.searchName) {
          params["creativeName"] = form.value.searchName;
        }
        if (campaignSelectItems.value.length > 0) {
          params["campaignIdList"] = campaignSelectItems.value;
        }
        if (unitSelectItems.value.length > 0) {
          params["unitIdList"] = unitSelectItems.value;
        }
        data = await getCreativeList(params);
        console.log("广告创意数据:", data);
        break;
      default:
        data = { list: [], total: 0 };
    }

    // 为每个表格数据项添加广告账户名称
    if (data && data.list && data.list.length > 0) {
      data.list = data.list.map(item => {
        // 如果已经有accountName，则不覆盖
        if (item.accountName) {
          return item;
        }

        // 根据adAccountId查找对应的广告账户名称
        const matchedAccount = adAccounts.value.find(
          account => account.adAccountId === item.adAccountId
        );
        return {
          ...item,
          accountName: matchedAccount
            ? matchedAccount.adAccountName
            : `账户ID: ${item.adAccountId}`
        };
      });
    } else {
      console.log("接口返回的数据列表为空或格式不符合预期:", data);
    }

    // 打印表格当前列配置
    console.log("当前表格列配置:", columns.value);

    dataList.value = data.list || [];
    pagination.value.total = data.total || 0;
  } catch (error) {
    console.error("获取数据失败:", error);
    ElMessage.error("获取数据失败");
    dataList.value = [];
    pagination.value.total = 0;
  } finally {
    loading.value = false;
  }
};

const onSearch = () => {
  pagination.value.currentPage = 1;
  loadTableData();
};

const resetForm = formEl => {
  if (!formEl) return;
  formEl.resetFields();
  form.value.timeZoneIana = "UTC+8";
  form.value.searchName = "";
  dateRange.value = [dayjs().subtract(7, "day").toDate(), dayjs().toDate()];
  form.value.dataBeginTime = dayjs().subtract(7, "day").valueOf();
  form.value.dataEndTime = dayjs().valueOf();
  dataList.value = [];
  pagination.value.total = 0;
  pagination.value.currentPage = 1;
  if (adAccounts.value.length > 0) {
    form.value.account = adAccounts.value[0].adAccountId;
  }
  onSearch();
};

// 广告计划选项数据
const campaignOptions = ref<any>({
  adCategory: [],
  budgetType: [],
  campaignType: [],
  cboAuthorized: [],
  deliveryStrategy: [],
  marketingType: []
});

// 获取广告计划选项数据
const loadCampaignOptions = async () => {
  try {
    const data = await getCampaignSelect();
    console.log("loadCampaignOptions = ", data);
    campaignOptions.value = data;
  } catch (error) {
    console.error("获取广告计划选项失败:", error);
  }
};

// 格式化状态显示
const formatStatus = (status: number) => {
  const statusMap = {
    0: { text: "未知", type: "info" },
    1: { text: "投放中", type: "success" },
    2: { text: "已暂停", type: "warning" },
    3: { text: "已删除", type: "info" },
    4: { text: "超预算", type: "danger" },
    5: { text: "预算不足", type: "danger" },
    6: { text: "审核中", type: "warning" },
    7: { text: "审核拒绝", type: "danger" },
    8: { text: "投放完成", type: "info" }
  };
  const statusInfo = statusMap[status] || { text: "未知", type: "info" };
  return h(ElTag, { type: statusInfo.type }, () => statusInfo.text);
};

// 格式化数值（转换为百分比）
const formatRate = (value: number) => {
  return value ? `${(value * 100).toFixed(2)}%` : "0%";
};

// 格式化金额（除以1000000）
const formatCost = (value: number) => {
  return value ? `${(value / 1000000).toFixed(2)}` : "0";
};

// 广告账号列表
const adAccounts = ref<{ adAccountId: number; adAccountName: string }[]>([]);

// 加载广告账号列表
const loadAdAccounts = async () => {
  try {
    const data = await getAdAccounts();
    adAccounts.value = data || [];
    // 默认选择第一个账户
    if (adAccounts.value.length > 0) {
      form.value.account = adAccounts.value[0].adAccountId;
    }
  } catch (error) {
    console.error("获取广告账号列表失败:", error);
  }
};

// 时区选项
const timeZoneOptions = [
  // { label: "UTC-5", value: "UTC-5" },
  // { label: "UTC-4", value: "UTC-4" },
  { label: "UTC-3 (巴西时间)", value: "UTC-3" },
  { label: "UTC+0", value: "UTC+0" },
  // { label: "UTC+1", value: "UTC+1" },
  // { label: "UTC+2", value: "UTC+2" },
  // { label: "UTC+3", value: "UTC+3" },
  // { label: "UTC+5", value: "UTC+5" },
  // { label: "UTC+6", value: "UTC+6" },
  // { label: "UTC+7", value: "UTC+7" },
  { label: "UTC+8 (北京时间)", value: "UTC+8" }
];

const dateRange = ref<[Date, Date]>([
  dayjs().subtract(7, "day").toDate(),
  dayjs().toDate()
]);

// 处理日期范围变化
const handleDateRangeChange = (dates: [Date, Date]) => {
  if (dates) {
    form.value.dataBeginTime = dayjs(dates[0]).valueOf();
    form.value.dataEndTime = dayjs(dates[1]).valueOf();
  } else {
    form.value.dataBeginTime = dayjs().subtract(7, "day").valueOf();
    form.value.dataEndTime = dayjs().valueOf();
  }
  onSearch();
};

// 基础搜索参数，可共享给选择器组件
const baseSearchParams = computed(() => ({
  timeZoneIana: form.value.timeZoneIana,
  dataBeginTime: form.value.dataBeginTime,
  dataEndTime: form.value.dataEndTime
}));

// 根据当前标签页获取搜索框的placeholder
const getSearchPlaceholder = () => {
  switch (activeTab.value) {
    case "campaign":
      return "搜索计划名称";
    case "unit":
      return "搜索广告组名称";
    case "creative":
      return "搜索创意名称";
    default:
      return "搜索名称";
  }
};

// 格式化出价策略
const formatDeliveryStrategy = (value: number) => {
  const strategyMap = {
    0: "未知",
    1: "出价上限",
    2: "目标成本",
    3: "最低转化成本",
    4: "目标成本上限"
  };
  return strategyMap[value] || "未知";
};

// 格式化推广目的
const formatMarketingType = (value: number) => {
  const typeMap = {
    0: "未知",
    1: "应用推广",
    2: "网站推广"
  };
  return typeMap[value] || "未知";
};

// 格式化数据源头
const formatDataSource = (value: number) => {
  const sourceMap = {
    0: "未知",
    1: "投放平台(手动)",
    2: "MAPI"
  };
  return sourceMap[value] || "未知";
};

onMounted(async () => {
  await loadAdAccounts(); // 加载广告账号列表
  loadCampaignOptions();
  loadTableData();
});
// watch(
//   () => createForm.value.deliveryStrategy,
//   newVal => {
//     // 当出价策略为最低转化成本或目标成本上限时，预算类型限定为不限
//     if (newVal === "3" || newVal === "4") {
//       createForm.value.budgetType = "1";
//     }
//   }
// );
</script>
<style scoped lang="scss">
.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}

.table-container {
  margin-top: 16px;
  background-color: #fff;
  padding: 16px;
  border-radius: 4px;

  :deep(.el-tabs__header) {
    margin-bottom: 16px;
  }

  :deep(.promotion-table) {
    // min-height: 400px;

    .el-table {
      min-height: 400px;
    }
  }
}
.tab-label {
  display: inline-flex;
  align-items: center;
}
custom-tabs {
  :deep(.el-tabs__header) {
    margin-bottom: 0;
  }

  :deep(.el-tabs__nav-wrap) {
    &::after {
      display: none;
    }
  }

  :deep(.el-tabs__nav) {
    background: var(--el-fill-color-light);
    border-radius: 4px;
    padding: 4px;
  }

  :deep(.el-tabs__item) {
    border-radius: 4px;
    height: 32px;
    line-height: 32px;
    padding: 0 16px;

    &.is-active {
      background-color: var(--el-color-white);
    }

    &:not(.is-active):hover {
      color: var(--el-text-color-regular);
    }
  }
}

.tab-label {
  display: inline-flex;
  align-items: center;
}
</style>
